package com.jn.exam.ucenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jn.exam.JwtUtils;
import com.jn.exam.MD5Util;
import com.jn.exam.R;
import com.jn.exam.ucenter.entity.Student;
import com.jn.exam.ucenter.service.AdminService;
import com.jn.exam.ucenter.service.OssFeignService;
import com.jn.exam.ucenter.service.StudentService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;

import static com.jn.exam.JwtUtils.APP_SECRET;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 江南大学1033190417
 * @since 2022-01-13
 */
@RestController
@RequestMapping("/ucenter/student")
public class StudentController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private OssFeignService ossFeignService;

    //根据学校给的编号登录
    @PostMapping("loginByNumber/{number}")
    public R loginByNumber(@PathVariable("number") String number, String password) {
        password = MD5Util.getMD5(password);
        Student student = studentService.loginByNumber(number, password);
        if (student != null) {
            if (student.getIsDisabled() == Boolean.TRUE) {
                return R.error().message("账号已禁用");
            }
            String token = JwtUtils.getJwtToken(student.getId(), student.getName(), student.getFaceGroupId());
            Student s=new Student();s.setId(student.getId()).setGmtModified(new Date());
            studentService.updateById(s);
            return R.ok().message("登录成功").data("token", token);
        }
        return R.error().message("登录失败");
    }

    @PostMapping("getUserInfo")
    public R getUserInfo(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String id = (String) claims.get("id");
        Student student = studentService.getById(id);
        return R.ok().data("student", student);
    }

    //退出登录
    @PostMapping("loginOut")
    public R loginOut(HttpServletRequest request) {
        return R.ok().message("退出登录成功");
    }

    //得到学生id
    @GetMapping("getStudentId")
    public R getStudentId(HttpServletRequest request) {
        String studentId = JwtUtils.getMemberIdByJwtToken(request);
        return R.ok().data("studentId", studentId);
    }

    //用手机号登录
    @PostMapping("loginByPhone/{phone}")
    public R loginByPhone(@PathVariable("phone") String phone, String code) {
        String PHONE = MD5Util.getMD5(phone);
        String CODE = redisTemplate.opsForValue().get(PHONE);
        if (code.equals(CODE)) {
            Student student = studentService.loginByPhone(phone);
            if (student != null) {
                if (student.getIsDisabled() == Boolean.TRUE) {
                    return R.error().message("账号已禁用");
                }
                String token = JwtUtils.getJwtToken(student.getId(), student.getName(), student.getFaceGroupId());
                return R.ok().message("登录成功").data("token", token).data("student", student);
            } else {
                return R.error().message("手机号不存在");
            }
        } else {
            return R.error().message("验证码错误");
        }
    }


    //更新(学生端)
    @PostMapping("update")
    public R updateStudent(@RequestBody Student student, HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        student.setId(id);
        boolean isUpdate = studentService.updateById(student);
        if (isUpdate) {
            return R.ok().message("更新成功");
        }
        return R.error().message("更新失败");
    }

    @PostMapping("updateById")
    public R updateById(@RequestBody Student student) {
        boolean update = studentService.updateById(student);
        if (update) {
            return R.ok().message("更新成功");
        }
        return R.error().message("更新失败");
    }

    //删除
    @DeleteMapping("deleteById")
    public R deleteById(String studentId) throws Exception {
        Student student = studentService.getById(studentId);
        String avatar = student.getAvatar();
        if (!StringUtils.isEmpty(avatar)) {
            ossFeignService.deleteFileByUrl(avatar);//删除头像
        }
        if (student.getIsRegisterFace()) {//将用户从某个用户组删除
            ossFeignService.deleteUserFromGroup(student.getFaceGroupId(), studentId);
        }
        studentService.deleteById(studentId);//删除学生这一列
        return R.ok().message("删除成功");
    }

    @ApiOperation("上传头像")
    @PostMapping("uploadAvatar")
    public R uploadAvatar(MultipartFile file, HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        Student student = studentService.getById(id);
        if (!StringUtils.isEmpty(student.getAvatar())) {
            boolean deleteFileByUrl = ossFeignService.deleteFileByUrl(student.getAvatar());
            if (!deleteFileByUrl) {
                return R.error().message("上传失败");
            }
        }
        String url = ossFeignService.uploadOssFile(file);
        student.setAvatar(url);
        boolean updateById = studentService.updateById(student);
        if (updateById) {
            return R.ok().message("上传成功");
        }
        return R.error().message("上传失败");
    }

    @ApiOperation("根据id查单条")
    @GetMapping("getById")
    public R getById(String id) {
        Student student = studentService.getById(id);
        return R.ok().data("student", student);
    }

    @ApiOperation("添加一个学生")
    @PostMapping("addOneStudent")
    public R addOneStudent(@RequestBody Student student) {
        String faceGroup = adminService.getOneFaceGroup();
        student.setFaceGroupId(faceGroup);
        boolean save = studentService.save(student);
        if (save) {
            return R.ok().message("添加成功");
        } else {
            return R.error().message("添加失败");
        }
    }

    @ApiOperation("查询id在某个数组中的学生，主要用于服务调用")
    @PostMapping("getStudentInIds")
    public R getStudentInIds(@RequestBody List<String> ids){
        QueryWrapper<Student> wrapper=new QueryWrapper<>();
        wrapper.in("id",ids);
        List<Student> students = studentService.list(wrapper);
        return R.ok().data("students",students);
    }

    //学号，姓名，年龄，性别
    @PostMapping("pageStudent")
    public R pageStudent(@RequestBody Student student, long current, long limit) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        String name = student.getName();
        String number = student.getNumber();
        Integer age = student.getAge();
        Integer sex = student.getSex();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(number)) {
            wrapper.eq("number", number);
        }
        if (age != null) {
            wrapper.eq("age", age);
        }
        if (sex != null) {
            wrapper.eq("sex", sex);
        }
        Page<Student> page = new Page<>();
        page.setCurrent(current).setSize(limit);
        studentService.page(page, wrapper);
        List<Student> students = page.getRecords();
        long rows = page.getTotal();
        return R.ok().data("rows", rows).data("students", students);
    }
}

